package com.gensdai.leliang.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.remoteInterface.URLConfig;
import com.gensdai.leliang.utils.BaseUtils;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/5/27.
 */

public class quick_login_two extends BaseActivityNoAbs implements View.OnClickListener {

    @BindView(R.id.user_phone)
    TextView user_phone;
    @BindView(R.id.auth_code)
    EditText auth_code;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.login)
    TextView login;
    @BindView(R.id.ui_title)
    TextView ui_title;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.tuwenyanzhengma)
    EditText tuwenyanzhengma;
    @BindView(R.id.tuwenma)
    ImageView tuwenma;

    private Upload up;
    private String phone;
    private String mm;
    private String invite_code;

    private final int LOGIN = 1; //注册返回标识
    private final int TIME = 2;// 设置点击间隔时间
    private final int GETTW = 4;// 获取图文验证码
    private int surplus_time = 60;
    private boolean get_note = true;
    private Bitmap bitmap = null;

    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case LOGIN:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            Toast.makeText(
                                    quick_login_two.this,
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                            if (new JSONObject((String) msg.obj)
                                    .getString("message").equals("手机认证短信发送成功")) {
                                handler.sendEmptyMessageDelayed(TIME, 1000);
                                get_note = false;
                            } else {
                                quick_login_two.this.finish();
                            }
                        } else if (new JSONObject((String) msg.obj)
                                .getString("message").equals("验证码输入有误")) {
                            gettw();
                        }
                        Toast.makeText(
                                quick_login_two.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case TIME:
                    if (surplus_time == 0) {
                        time.setText(getResources().getString(R.string.get_auth_code));
                        surplus_time = 60;
                        get_note = true;
                    } else {
                        surplus_time--;
                        time.setText(surplus_time + getResources().getString(R.string.time));
                        handler.sendEmptyMessageDelayed(TIME, 1000);
                    }
                    break;
                case GETTW:
                    if (bitmap != null) {
                        tuwenma.setImageBitmap(bitmap);
                    } else {
                        Log.e("空值", "空值");
                    }

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quick_login_two);
        ButterKnife.bind(this);
        init();
        setonclick();
        gettw();
    }


    /**
     * 初始化
     */
    private void init() {
        ui_title.setText(getResources().getString(R.string.quick_login));
        phone = getIntent().getStringExtra("phone");
        mm = getIntent().getStringExtra("mm");
        invite_code = getIntent().getStringExtra("invite_code");
        user_phone.setText(phone);
//        handler.sendEmptyMessageDelayed(TIME, 1000);
        up = new Upload(this);
    }

    /**
     * 设置点击事件
     */
    private void setonclick() {
        login.setOnClickListener(this);
        time.setOnClickListener(this);
        back.setOnClickListener(this);
        tuwenma.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                if (auth_code.getText().toString().trim().length() == 4) {
                    RegisterRequest2Str();
                } else {
                    Toast.makeText(quick_login_two.this, getResources().getString(R.string.auth_code_error), Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.time:
                if (get_note) {
                    RegisterRequest2Str();
                } else {

                }
                break;
            case R.id.back:
                quick_login_two.this.finish();
                break;
            case R.id.tuwenma:
                gettw();
                break;
            default:
                break;
        }
    }


    /**
     * 获取图文验证码
     */
    private void gettw() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("type", "app");
        toStrTW(loginParams);
    }

    //返回字符串类型
    private void toStrTW(Map<String, String> loginParams) {
        Call<ResponseBody> call = ApiService.getInstance(this).MAKE_VERIFY_CODE(loginParams);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                bitmap = BitmapFactory.decodeStream(response.body().byteStream());
                Log.e("流", response.body().byteStream().toString());
                if (bitmap != null) {
                    handler.sendEmptyMessage(GETTW);
                    Log.e("有", "*------");
                } else {
                    Log.e("无", "*------");
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

    }

    /**
     * 调用发短信接口
     */
    private void RegisterRequest2Str() {
        //获取edit的值后请求

        String password = mm;

        if (TextUtils.isEmpty(password)) {
            return;
        }

        String resultPassword = BaseUtils.EncryptedPassword(password);
        Log.d("password", resultPassword);

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("phone", phone);   //手机号
        loginParams.put("password", resultPassword);                  //密码
        loginParams.put("inviteCode", invite_code);                //邀请码
        loginParams.put("inputCode", auth_code.getText().toString().trim());                 //输入的验证码
        loginParams.put("inputVerifyCode", tuwenyanzhengma.getText().toString().trim()); //图文验证码
        loginParams.put("isNext", "false");                 //不是下一步
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).Register2Str(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = LOGIN;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage() + "/n" + e.getStackTrace());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

}
